Jason Sperske
Jason Sperske

Reputation: 30416

What is the equivalent of a Servlet (Java class that extends HttpServlet in tomcat) in an ASP.net project?

I started programming my own web applications during the beginning of the Apache Tomcat project, and thus when I am writing a Servlet that responds with some small piece of JSON to some GET or POST my code would look something close to this:

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());
  }
}

My question is "what is the equivalent method/design/New Item for ASP.net?"

I have been writing these as WebForms that look like this:

First the (basically empty) .aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SimpleServlet_json.aspx.cs" Inherits="com.stackoverflow.question.SimpleServlet_json" %>

Then this .cs file:

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; }
  }
}

But I secretly worry that I am asking my fellow c# programmers to adopt a non-intuitive style.

These examples are rather contrived, in practice they are used as the JSON representation of a database entity. For an example the URL example.com/product/1 is the HTML version (with a JSP or ASPx page associated with the URL) while example.com/product/1.json is the JSON representation (with one of these classes). I'm a fan of URL Rewriting.

Upvotes: 10

Views: 25003

Answers (5)

percentor
percentor

Reputation: 41

More like Owin

'OWIN defines a standard interface between .NET web servers and web applications.'

Upvotes: 1

karim
karim

Reputation: 15589

I had a similar question and some research on it ended to Web API. Wanna share with SO.

In the MSDN site, http://msdn.microsoft.com/en-us/library/jj823172(v=vs.110).aspx

Found a video tutorial where they said that for machine cosumption like iPhone or web app clients of JSON or xml, web API is recommended option. Its around the last part of the video.

While for more complex machine to machine communication WCF is prefereable.

http://channel9.msdn.com/Series/Building-Web-Apps-with-ASP-NET-Jump-Start/Building-Web-Apps-with-ASPNET-Jump-Start-04-Building-a-Service-Layer-with-ASPNET-Web-API

Here is a screenshot from their presentation.

enter image description here

Upvotes: 2

OakNinja
OakNinja

Reputation: 2346

HttpHandlers should do it in any version .NET version after 2003. see this Microsoft article.

However, a more modern (and more intiutive) approach would be to use .NET MVC or more specifically .NET Web API.

Quote from Scott Gu's blog on his asp.net 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:"

And the official Microsoft .NET Web API page states:

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.

Upvotes: 9

cmd.prompt
cmd.prompt

Reputation: 954

I think you are looking for a Generic Handler (.ashx)

<%@ WebHandler Language="C#" Class="MyHandler" %>

using System;
using System.Web;

public class MyHandler : IHttpHandler 
{
    public void ProcessRequest (HttpContext ctx) 
    {
        var json = new JSONResonse()
        {
            Success = ctx.Request.QueryString["name"] != null,
            Name = ctx.Request.QueryString["name"]
        };

        ctx.Response.ContentType = "application/json";
        ctx.Response.Write(JsonConvert.SerialzeObject(json));
    }

    public bool IsReusable {
        get { return false; }
    }
}

Make requests to them the same as you would your pages. yoursite.com/my-handler.ashx?name=foo

Upvotes: 3

scartag
scartag

Reputation: 17680

I can't really say i can draw parallels between a Servlet and some type on asp.net, as webforms is quite different.

From your sample code i can recommend that you take a look at asp.net webapi as this will map quite well to what you are currently trying to do.

Upvotes: 1

Related Questions