c# – 在ASP.net项目中,Servlet(在tomcat中扩展HttpServlet的Jav
我开始在Apache Tomcat项目开始时编写自己的Web应用程序,因此当我编写一个Servlet,用一些小的
JSON响应某些GET或POST时,我的代码看起来会接近这个:
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重写的粉丝. 解决方法
HttpHandlers应该在2003年之后的任何版本的.NET版本中执行它.请参阅此
Microsoft article.
但是,更现代(和更具创造性)的方法是使用.NET MVC或更具体的.NET Web API. 从他的asp.net博客上的Scott Gu’s blog引用:
并且official Microsoft .NET Web API page指出:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |