对于(非SOAP,非WSDL)Web服务项目,最佳的ASP.NET文件类型是什么?
时间:2020-03-06 14:44:29 来源:igfitidea点击:
自VS 2003以来没有进行过ASP.NET开发,因此我想节省一些时间并从其他错误中学习。
编写一个Web服务应用程序,而不是WSDL / SOAP / etc。 -更像REST + XML。
如果我想通过同一个URI分别处理不同的HTTP动词,那么"新建项"选项(Web窗体,通用处理程序,ASP.NET处理程序等)中的哪一个最有意义。在理想的情况下,我希望通过代码而不是通过web.config声明式地进行分派-但是,如果这样使生活变得太艰辛,则可以改变。
解决方案
如果我们不使用内置的Web服务(.asmx),则可能应该使用通用处理程序(.ashx)。
如果需要休息,可能是MVC。
我同意ashx,可以为我们提供最大的控制权。我们还可以更加复杂,并创建自定义Http处理程序。这样,我们就可以拦截自己决定的任何扩展。当然,我们可以添加一个Http模块并将任何请求重写为通用ashx处理程序。
这是我一直在使用的想法...使用风险自负,代码位于我的"沙盒"文件夹中;)
我想我想摆脱使用反射来确定要运行哪种方法的方法,而使用HttpVerb作为键在字典中注册委托可能会更快。无论如何,此代码不提供任何担保,等等,等等。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
REST服务使用的动词
public enum HttpVerb
{
GET, POST, PUT, DELETE
}
在服务上标记方法的属性
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
public class RestMethodAttribute: Attribute
{
private HttpVerb _verb;
public RestMethodAttribute(HttpVerb verb)
{
_verb = verb;
}
public HttpVerb Verb
{
get { return _verb; }
}
}
休息服务的基类
public class RestService: IHttpHandler
{
private readonly bool _isReusable = true;
protected HttpContext _context;
private IDictionary<HttpVerb, MethodInfo> _methods;
public void ProcessRequest(HttpContext context)
{
_context = context;
HttpVerb verb = (HttpVerb)Enum.Parse(typeof (HttpVerb), context.Request.HttpMethod);
MethodInfo method = Methods[verb];
method.Invoke(this, null);
}
private IDictionary<HttpVerb, MethodInfo> Methods
{
get
{
if(_methods == null)
{
_methods = new Dictionary<HttpVerb, MethodInfo>();
BuildMethodsMap();
}
return _methods;
}
}
private void BuildMethodsMap()
{
Type serviceType = this.GetType();
MethodInfo[] methods = serviceType.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (MethodInfo info in methods)
{
RestMethodAttribute[] attribs =
info.GetCustomAttributes(typeof(RestMethodAttribute), false) as RestMethodAttribute[];
if(attribs == null || attribs.Length == 0)
continue;
HttpVerb verb = attribs[0].Verb;
Methods.Add(verb, info);
}
}
public bool IsReusable
{
get { return _isReusable; }
}
}
REST服务样例
public class MyRestService: RestService
{
[RestMethod(HttpVerb.GET)]
public void HelloWorld()
{
_context.Current.Response.Write("Hello World");
_context.Current.Response.End();
}
}

