package com.stackoverflow.question;
import java.io.IOException;
import javax.servlet.servletexception;
import javax.servlet.http.*;
import org.json.*;
public class SimpleServlet_json extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,servletexception {
request.setCharacterEncoding("UTF-8");
JSONObject json = new JSONObject();
try {
json.put("Success",true);
json.put("Name",request.getParameter("name"));
} catch (JSONException e) {}
response.setContentType("application/json");
response.getoutputStream().print(json.toString());
}
}
我的问题是“ASP.net的等效方法/设计/新项目是什么?”
我一直把它们写成WebForms,看起来像这样:
首先(基本上是空的).aspx文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SimpleServlet_json.aspx.cs" Inherits="com.stackoverflow.question.SimpleServlet_json" %>
然后这个.cs文件:
namespace com.stackoverflow.question
{
public partial class SimpleServlet_json : System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
var json = new JSONResponse()
{
Success = Request.QueryString["name"] != null,Name = Request.QueryString["name"]
};
Response.ContentType = "application/json";
Response.Write(JsonConvert.SerializeObject(json));
}
}
[Serializable]
class JSONResponse
{
public string Name { get; set; }
public bool Success { get; set; }
}
}
但我暗自担心我要求我的同事c#程序员采用非直观的风格.
这些示例相当人为,实际上它们被用作数据库实体的JSON表示.例如,URL example.com/product/1是HTML版本(具有与URL关联的JSP或ASPx页面),而example.com/product/1.json是JSON表示(具有这些类之一).我是URL重写的粉丝.
解决方法
但是,更现代(和更具创造性)的方法是使用.NET MVC或更具体的.NET Web API.
从他的asp.net博客上的Scott Gu’s blog引用:
“Our new ASP.NET Web API support enables you to easily create powerful
Web APIs that can be accessed from a broad range of clients (ranging
from browsers using JavaScript,to native apps on any mobile/client
platform). It provides the following support:”
并且official Microsoft .NET Web API page指出:
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients,including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.