开发者

What's the easiest way to get a web request into C# code?

So... I've got an ASP.NET app. Let's assume I configure IIS to always point to the same file, index.aspx. Let's say I want to write all my code in C# and then return some HTML I generated in the C#. How do I do that?

Would I just have 1 file with 1 line of code,

<%@ Page CodeBehind="mycode.cs"

Is it necessary to have such a "useless" file? I can't direct the request straight into the code-behind?

Secondly, where are some good tutorials on code-behinds? Specifically, I see this Page_Load event that I guess gets called automatically?

  • Are there other events? What are they?
  • Also, how would I access things like POST data, or the request 开发者_如何学运维URL?
  • How would I return a HTML response? Or a 404?

I'm seeing a lot of tutorials on "inline" ASP, but I don't really care about that.


Sounds like you want a generic handler. They are available in the New Item... dialog. This will give you a .ashx file where you can handle incoming web requests just like you would in your scenario, but in a cleaner way. Using these you can return any kind of HTTP response, including HTTP errors. You have full access to the HTTP context for POST data, URL parameters, cookies, etc. See more here.

Another alternative is to implement IHttpHandler yourself, although with generic handlers there isn't much point in going through the effort.


Are there other events? What are they?

There is a whole lot of Events available when you inherit from System.Web.UI.Page. You can see them http://msdn.microsoft.com/en-us/library/ms178472.aspx

Also, how would I access things like POST data, or the request URL?

this.Request.Form, would let you access the PostData from a page. this.Request.Url would let you access the url.

How would I return a HTML response? Or a 404?

You can override the Render method of the page to provide HTML Response. You can throw a HttpException(404, "file not found") to return 404.

After going through your questions, you most likely need ASP.NET MVC rather than ASP.NET webforms or you can use a handler as suggested by Martin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜