MVC :: How To Test Action Which Alters Http Response

Apr 27, 2010

How can I unit test an action which alters the Http Response object? I haven't been able to solve this. I can mock the object but can't see how I can check the value after the action runs. I set the Response.StatusCode when errors occur in ajax requests and need to check it has been set in the unit test. The only alternative I can see is to change all my actions to return json objects with a IsSuccessful flag or similar.

View 5 Replies

Similar Messages:

Web Forms :: Response.Redirect ("http://www.") - Internet Security Doesn't Permit To Install "Test.exe"

Nov 5, 2010

I put this code in my aspx file :


when I access my aspx file through Internet I can download the file "Test.exe" but my internet security doesn't permit to install it. Has anyone had this problem?

View 2 Replies

Test That A Controller Action Simply Returns A Link To Another Action?

Apr 29, 2010

Lets say I have a simple controller for ASP.NET MVC I want to test. I want to test that a controller action (Foo, in this case) simply returns a link to another action (Bar, in this case).How would you test TestController.Foo? (either the first or second link)

My implementation has the same link twice. One passes the url throw ViewData[]. This seems more testable to me, as I can check the ViewData collection returned from Foo(). Even this way though, I don't know how to validate the url itself without making dependencies on routing.The controller:

public class TestController : Controller
public ActionResult Foo()[code].....

View 1 Replies

MVC :: Create Action Not Carrying Model Across To Http Action

Jun 12, 2010

My httppost action doesnt seem to have received my model. The code is below;


i put a breakpoint on the line; return RedirectToAction("Error", "Dashboard"); and i found that appQualif carried no values whatsoever from the form i submitted..

View 5 Replies

MVC :: Unable To Unit Test The Custom Action Filter

Jul 17, 2010

I have a custom actionfilter that strips out the whitespaces before the html is rendered in browser and it is working fine. However I have been unable to unit test the custom action filter. Ideally I want to do an assert on the sample html that all whitespaces have been removed. Code looks something like this.


View 1 Replies

MVC :: Pass ID Value To Home Controller Index Action? (like

Jun 18, 2010

I want to have the following URL pattern in my MVC application: -> display welcome page -> display article with ID 5

I have set up my Home Controller like this:


When I request, everything works as expected (the Index action is invoked with the ID parameter set to NULL).

But when I request it says: HTTP 404 Resource not found. When I request it works.

View 2 Replies

Want To Try And Test An Action Method On Controller That Itself Tests If IsAjaxRequest() Is True?

May 28, 2010

I'm just starting to use the TestHelpers in MvcContrib. I want to try and test an action method on my controller that itself tests if IsAjaxRequest() is true. I've used the same code that is shown in the TestHelper samples to set up the TestControllerBuilder

_controller = new StarsController();
_builder = new TestControllerBuilder();

So that _controller has all the faked/mocked HttpContext inside it, which is really great. But what do I do now to force IsAjaxRequest() on the internally faked Request object to return true?

View 2 Replies

C# - Test A MVC2 Post Action With Validation When Using MvcContrib TestHelper?

Oct 12, 2010

I'm attempting to write a unit tests for an ASP.NET MVC 2 post action that takes a view model as its sole parameter. The view model is decorated with validation attributes such as [Required]. I'd like to test two scenarios. The first scenario is when a valid set of data is passed in (ie, all required properties have values) and a redirect to the list page is returned. The second scenario involves passing in invalid data (eg, when one or more of the Required properties are not set). In this case the same view is returned with error messages.The action signature is as follows:

public virtual ActionResult Create(NewsViewModel model)

The NewsViewModel class is as follows:

public class NewsViewModel
public Guid Id { get; set; }


View 1 Replies

The HTTP Verb POST Used To Access Path '/test.html' Is Not Allowed

Feb 5, 2010

Below is my code:


The HTTP verb POST used to access path '/test.html' is not allowed

View 4 Replies

Mvccontrib Test Helper And Verifying Http Post Routes And Parameters?

Jan 29, 2010

In my MVC app, I have two methods on a controller, one for when the user first arrives on the view and then one when they submit the form on said view.

public ActionResult Foo() {}
public ActionResult Foo(string id, Account accountToFoo) {}

In the second action, there's a custom model binder that's assembling the account object that I'm acting on, though that's really not important. This all works fine in testing locally on a server.We try to be pretty good about writing unit tests to test all our different views are properly getting routed to, including those that are HTTP POST. To do so, we've been using mvccontrib's test helper.

Testing gets have been super simple

ShouldMapTo<AccountController>(c => c.Foo("myusername"));

My question is in testing POST routes, how do I write the lambda that I would use to verify the post is receiving accurate values, similar to the GET test above?

For a POST, it looks something like:

ShouldMapTo<AccountController>(a => something_something);

It's the something_something portion of my lambda that I'm having trouble with. Using arbitrary values doesn't work ("a => a.Foo(0, new Account()"). How would I specify the expected values as part of the test?EDIT I was hoping there was something akin to the way Moq has lambdas for statements such as foo.Setup(s => s.Foo(It.IsAny(), It.Is(i => i > 32)) and so on. Even I have to explicitly supply the values, that's workable--I just can't seem to grok the desired structure to pass those explicit values.

View 2 Replies

VS2010 Web Performance Test - No Hidden Field Detected On Large Response

Feb 19, 2011

I have a web performance test which contains a request whose response is greater than 5MB, and the Extract Hidden Fields rule fails to find (necessary and required!) hidden fields in the response. Response header contains

HTTP/1.1 200 OK
Transfer-Encoding : chunked
Vary : Accept-Encoding, User-Agent
Cache-Control : private
Content-Type : text/plain; charset=utf-8
Date : Sat, 19 Feb 2011 15:24:38 GMT
Server : Microsoft-IIS/6.0
X-AspNet-Version : 2.0.50727
X-Powered-By : ASP.NET

Other than that and the response size, there is nothing remarkable about this scenario. In fact, this same test succeeds when a smaller data set is used. I suspect the Web Performance Test framework is having issues parsing the "chunked" encoding or sheer volume of data. Ahem, how can I obtain these required hidden fields from my response? ie resolutions, work arounds, converting auto-extraction to manual, etc.

View 1 Replies

Abort/cancel Action And Response From ActionFilter?

Mar 3, 2011

Best way to abort/cancel action from ActionFilter

I've got this ActionFilter, and it's suppose to end the connection immediately and return a 401 Unauthroized:

public class SignInRequired : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext filterContext)[code]....

I learned how you can cancel the action from executing by setting 'context.Result = new EmptyResult()` here, but I'm not sure if this is the best way to flush the response and close the connection.

View 1 Replies

C# - MP3 Download In An HTTP Response?

Jun 9, 2010

I've a question about something I'm searching for,for too long! We've build an application from which an admin upload songs into a database. Then user can bought songs and download it individualy. The problem is that when user download MP3 songs with the code below, it works great in Firefox and Chrome but not in IE8 simply because WMP trying to open the songs and it just don't get it instead of having a "Save as" dialog? Any issue on HOW can i force to have the "Save As" diaglog? Note that I have not MP3 physicaly on server it's in database. So I can't direct link to song ...

Here's my code :

// Remove "specials chars"
foreach (char aChar in @"/:*?""<>| ") {
if (aChar == ' ') {
songNameAndExt = songNameAndExt.Replace(' ', '_');
} else {
songNameAndExt = songNameAndExt.Replace(aChar.ToString(), string.Empty);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.Headers.Add("Content-Disposition", string.Format("filename={0}", songNameAndExt));
HttpContext.Current.Response.OutputStream.Write(songData, 0, songLength);

View 1 Replies

MVC :: Modifying Response Content After Controller Action Executed?

Mar 18, 2011

Is there a way of modifying the response in OnResultExecuted? Like reading the current response and writing it out again?

I want to replace date string in JsonResult after the object was serialized.

View 6 Replies

HTTP Response And Request In Binary

Feb 21, 2010

I need to I can make the web request to a webservice which take a XML argument. And is expected to return a Binary response. I am able to make the request but while recieving the response back I am unable to get the response in binary. When I read the response
using streamreader see the header and some attached "HEBRISH" words probably binary but unable to sepreate it out. Please help in seprating out the binary the response data.

View 1 Replies

Web Forms :: Get Response Value - From Http Post

Mar 23, 2011

What wrong with this code?


I would like the numeric values of the enum of Response.StatisCode

View 1 Replies

Custom HTTP Response C# And Ajax?

Apr 4, 2011

I'm trying to query a database that contains information about a "ticket" using jQuery's .ajax() method.

type: 'GET',
url: 'Preview.ashx',
data: 'ticketID=' + ticketID,
success: function (data) {
// 'data' should be a row from the database, so it should be like an
// array that contains each column of the row
// do stuff with this data
... so that all works fine. I'm having trouble with the data variable. On the server side, I do...
// get the ticket ID from the POST parameter
int ticketID = context.Request["ticketID"] != null ? Convert.ToInt32(context.Request["ticketID"]) : -1;
if (ticketID >= 0) {
// grab the data from the database, getInfo() will retrieve the row
// in the DB that corresponds to the ticket ID given, returning an
// ArrayList with all of the information
ArrayList theTicket = getInfo(context, ticketID);
// now, I need to somehow return this information so that I could deal with it
// in the 'success' callback function above
} else {
// something went wrong with the 'newTicket' POST parameter
context.Response.ContentType = "text/plain";
context.Response.Write("Error with 'ticketID' POST parameter.

I've debugged this enough to be sure that the ArrayList contains the correct information. Now I just need to return it. How would I do this? How would I return the data in the ArrayList? Is it possible to structure the response so that I could do data.ID, data.otherColumnName, etc... in the callback function to access the different fields?

View 3 Replies

Suppressing HTTP 500 Response Codes

Feb 10, 2010

I've had a bit of feedback from some threat and vulnerability folks relating to websites returning HTTP 500 response codes. Essentially the advice is that all possible measures must be taken to avoid the server throwing a 500 (i.e. extensive form input validation) which is fine. However, the advice also suggested that attempts to compromise security by means such as inserting a tag into a random query string causing ASP.NET request validation to fire or manipulating viewstate also should not return an HTTP 500. Obviously the native framework behaviour is to interpret the request and possibly throw to a custom error page but even this will return a 500 response code.

So I'm after some thoughts on how to approach this. Is there any way to configure the app at either the .NET level or IIS level to return an HTTP 200 when a 500 is raised? Or does this become a coding exercise at global.asax level in one of the application events? Are there other consequences to consider? BTW, the rationale from the security side is that apps which return HTTP 500 may be viewed as "low hanging fruit" by bots randomly scanning for vulnerabilities and prompt further malicious activity. attempts I'm personally not convinced that changing response codes offers any real security gains but am happy to hapy to take the advice of the pros.

View 3 Replies

Response - Get Custom Http Header?

May 14, 2010

I have an appliction on the one server. There I've added code on server-side in Page_Load:

Response.AddHeader("key", "password-key-from-hotel");

On the client side I have a form:
<form ... action="" >
<input type="hidden" id="asd" value="fgh" >
<script type="text/javascript">

Then on the other domain - there is also my other application - I'm trying to get the hedaer "key" by this code:


But there is no such header. Is there is a desicion? Where is my mistake?

View 2 Replies

Add Response Http Headers In Web Configuration?

May 27, 2010

In my application I need to set a http response header. I'd like to do this in web.config. but I dont'know if this is possible and I can't find it on Google. Solution Finally, after a long search I found the solution. Create a class with this code:

public class myHTTPHeaderModule : IHttpModule
#region IHttpModule Members
public void Dispose()
public void Init(HttpApplication context)
context.EndRequest += new EventHandler(context_EndRequest);
void context_EndRequest(object sender, EventArgs e)
HttpResponse response = HttpContext.Current.Response;
response.AddHeader("Content-Language", "*");

(Don't ask me why to use this event, but it works..) Now add a line in web.config in the HttpModule section:

<add type="namespace.myHTTPHeaderModule, assembly name" name="headers" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

View 4 Replies

C# - Exactly Does Response.Redirect("~/...") Put In The HTTP Response?

Nov 24, 2010

I've just finished reading URL vs. URI vs. URN, in More Concise Terms, and it's really helped understand the distinction between the three terms. Since then I've skimmed the RFC2141 and RFC2616 specs and Microsoft's Response.Redirect Method documentation in an effort to answer the following question confidently.

Given this line of code:


And this resulting HTTP response (trimmed for context):

Status=Found - 302 Date=Wed, 24 Nov
2010 17:27:58 GMT

What name(s) most properly describes what has been placed into the "Location" header?

URL? URI? URN? URC? Which is it?

View 5 Replies

Creating Dynamic Http Response From Component

May 14, 2010

I've developed a component which processes online payments. At a specific point the user must be redirected to the selected acquirer web site for authentication. The acquirer itself suggests that there should be a web page which does it. Something such as the following,

<html xmlns="[URL]">
<head id="Head1" runat="server">
<script type="text/javascript">
function Go() {
<body onload="Go();">
<form id="form1" runat="server" method="post" action="/...">
<asp:HiddenField ID="MID" runat="server" />
<asp:HiddenField ID="Amount" runat="server" />
<asp:HiddenField ID="ResNum" runat="server" />
<asp:HiddenField ID="RedirectURL" runat="server" />

This page redirects the user and posts required arguments to the acquirer's web site. Prior to this page there is another page with a payment button (for example). In the click event of the payment button my component is instantiated and required calculation is done. Something such as the following,

protected void btnPayment_Click(object sender, EventArgs e)
var paymentProcessor = new NS.PaymentProcessor(/*required arguments*/);
NS.Result result = paymentProcessor.Calc();
Session.Add("PaymentProcessResult", result);
catch (Exception p)
throw p;

What I'm going to do is to generate [TakeOff.aspx] page at run-time by the payment processor component instead of having static page (I mean aspx pages that are generated during development phase). The reason why is that we may have different acquirers and each acquirer requires its own arguments to be posted. So if the payment processor component generates aspx or even html pages at run-time we do not need recompile and redeploy the web application.

My problem is that I do not know how to generate aspx pages at run-time. I'm not an ASP.NET guru and all efforts that I've made using HttpResponse were in vain as the original page does not transfer the control to the generated page.

View 1 Replies

HTTP Response Behavior - Cause Browser To Prompt

Jan 5, 2011

I have two very similar pieces of ASP.NET code that send a file in an HTTP Reponse to the client. They should cause the browser to prompt to save the file. The first one works, the second one doesn't. The HTTP responses as seen in Fiddler are below.

HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 228108
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
content-disposition: attachment; filename=Report.xlsx
Date: Wed, 05 Jan 2011 12:17:48 GMT
<binary data>

Not working:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/
Date: Wed, 05 Jan 2011 12:19:21 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 228080
content-disposition: attachment; filename=report 2.xlsx
Cache-Control: private
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Connection: Close
<binary data>

When the first one is seen in Fiddler the browser correctly prompts to save the file. When the second one is seen in Fiddler, nothing observable happens in the browser. Same behaviour in both chrome and firefox.

EDIT: ASP.NET code that produces the second response

Response.Buffer = false;
Response.ContentType = @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-length", genstream.Length.ToString());
Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", filename));
byte[] buffer = new byte[1024];
genstream.Position = 0;
int n;
while ((n = genstream.Read(buffer, 0, 1024) ) > 0)
Response.OutputStream.Write(buffer, 0, n);

View 4 Replies

Sending OK Response Over HTTP To Webpage Request

May 12, 2010

I am using an SMS Gateway to make my application receive SMSs. For this, the SMS Gateway sends a request to one of the pages in my application with the message as a querystring parameter. eg.[URL]. Now after my page gets invoked, I need to send an OK response to the SMS Gateway so that it doesn't keep retrying to send the same message to my application again and again. I cannot figure out how to send the OK response.

View 1 Replies

Raw HTTP Response Shown In Browser Instead Of Being Rendered

Jul 23, 2010

we're facing a weird and seemingly randomly appearing problem where the browser renders the complete, raw HTTP response (to a GET request) including all headers and the compressed content as text instead of just using the contents and rendering it. This happens for whole page loads as well as postbacks as well as page loads inside an iframe; for sure in Firefox 3.6.*, not sure about IE right now.

Our service is an ASP.NET 2.0 web app running on IIS 7.5, on our test machines we regularly have Fiddler running in the background (wondering if this might be part of the problem).

This behaviour occurs very rarely but we have started seeing this problem lately during our tests.

Has anybody encountered this problem before and knows what causes it and maybe even knows what to do about it?

View 1 Replies

Copyrights 2005-15, All rights reserved