C# Response.Write Error from scaffolded "dotnet new mvc" - c#

I'm familiar with PHP and JS, as well as MVC methodology, but I'm completely new to C# and have spent time looking for the documentation on this specific error.
I used dotnet new mvc to create a working app on port 5000. Also note, I am working in the Controller, not the model or view:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ExelonPrime.Models;
namespace OptimusPrime.Controllers{
public class ApiController : Controller
{
public void Help_Pdf()
{
Response.Write("test");
}
}
}
And the error I get (when trying to compile) is:
error CS1061: 'HttpResponse' does not contain a definition for 'Write' and no accessible extension method 'Write' accepting a first argument of type 'HttpResponse' could be found (are you missing a using directive or an assembly reference?)
If I'm missing a using directive, which one is it? I tried System.Web and that didn't work. How do I make this work?

I would recommend following through microsofts tutorial on using asp.net core.
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/?view=aspnetcore-2.2
As far as this specific instance, rather than using Response.Write, I would do this
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SampleWeb.Models;
namespace SampleWeb.Controllers
{
public class ApiController : Controller
{
[HttpGet]
public ActionResult<string> Help_Pdf()
{
return "test";
}
}
}
This specific sample might be helpful.
With this class, the url https://localhost:5001/api/Help_Pdf returns "test"

In ASPNET Core, when writing an API, it's more common to return an object, or POCO in stead of directly writing to the response stream (although it indeed is possible)
try changing your
public void Help_Pdf()
{
Response.Write("test");
}
to
[HttpGet()]
public IActionResult Help_Pdf()
{
return Ok();
}
this will return an 204 (no content), you can pass data however, to the OK function, to add a body to the response object.

If your trying to write directly to the response stream like that, you can do this:
public async Task Help_Pdf()
{
await Response.WriteAsync("Test");
}
However, I'd recommend not doing this in your actual app, the method should return an IActionResult. IMO it's not good practice to write directly to the stream in your controller methods (not very test friendly).

Related

Is it possible to reference ModelContext of an existing Project inside generated Controllers with Sourcegenerators

I'm currently playing around with SourceGenerators and want to create a controller for each model of an existing DBContext.
I kickstarted the project with Scaffold-DbContext DemoDatabase and added the Person controller and the API is working fine. The project is in net6.0 and the generator is in netstandard2.0.
My handwritten Controller in the API Project looks exactly the same as the generated Code.
I managed to create the following file via the SourceGenerator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Deltas;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using DemoApi.Models;
namespace DemoApi.Controllers.v3
{
public partial class PersonController : ODataController
{
private ModelContext _context;
public PersonController(ModelContext context)
{
_context = context;
}
[HttpGet]
[EnableQuery]
public IActionResult Get()
{
return Ok(_context.Person.ToList());
}
}
}
However VisualStudio outputs an Error stating that the ModelContext does not contain a definition for Person. Either the syntax highlighting is not working properly or the I'm missing something because I can't navigate the generated files (eg. pressing F12 on ODataController just outputs: Cannot navigate to the symbol under the caret.)
Are there any possible way for the generated files to recognize the existing ModelContext because referncing is via using DemoApi.Models did not work or am I missing something?
Any help would be greatly appreciated
Thanks in advance

WebAPI not accepting Post Requests Successfully

My controller for one of my WebAPIs was working perfectly yesterday, but today I made some changes to projects outside of the actual controller code and now the API is not posting correctly. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Markup;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace SanTool_WebAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class GeneratorStatusController : ControllerBase
{
static List<string> strings = new List<string>()
{
"value0", "value1", "value2"
};
[HttpGet]
public List<string> GetValues()
{
return strings;
}
[HttpPost("{input}")]
public List<string> Post(string input)
{
strings.Add(input);
return strings;
}
}
}
When I run the code using IIS explorer, and then navigate to https://localhost:44312/GeneratorStatus/, it displays my [HttpGet] correctly (displays the three strings), but when I try to use the post request with, https://localhost:44312/GeneratorStatus/2, it gives me error 405 and doesn't return the string
If you are just changing the URL in chrome this would be the problem. 405 often will mean that you are using the wrong http request type. When just changing the URL browsers issue a GET request to that resource.
You may want to test that same POST method with Postman.
Also see: Asp.Net Core 3.1 405 Method Not Allowed
First thing first.
I could be wrong here, but https://localhost:44312/GeneratorStatus/2, is something I would only use when I am getting things. In my experience, I have never seen a POST URL that looks like that.
Second,
I think, you are doing the Post wrong. First Up, I hope you are using Postman or curl to test your endpoints.
your POST would be something like this.
URL - If I am POSTing, the URL would be
https://localhost:44312/GeneratorStatus
with the Post Body, in your case, is a simple string, would look something like this.
{
input : "some input value"
}
Your Controller should probably look like this.
[HttpPost]
public List<string> Post(string input)
{
strings.Add(input);
return strings;
}

The type arguments for method 'CommandService.AddModuleAsync<T>(IServiceProvider)' cannot be inferred from the usage

I'm trying to make a bot with this tutorial https://www.youtube.com/watch?v=egq26JwyJkc (11:47) and with the same code I'm getting this error
The type arguments for method 'CommandService.AddModuleAsync<T>(IServiceProvider)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Even with programming knowledge it's hard to understand what is going on here...
This is my code
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace forTesting
{
public class CommandHandler
{
private DiscordSocketClient _client;
private CommandService _service;
public CommandHandler(DiscordSocketClient client)
{
_client = client;
_service = new CommandService();
_service.AddModuleAsync(Assembly.GetEntryAssembly());
}
}
}
This means you need to specify what T is.
Try specifying T based on the generic method limitations.
A little late to the party but hopefully someone may find this information helpful with regards to the above issue. After an update modules are built when added to the CommandService, as well as on command execution. As such, an IServiceProvider is now required for the building phase of modules.
So the answer you are looking for is:
await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), _service);
Pass null for the IServiceProvider.
_service.AddModuleAsync(Assembly.GetEntryAssembly(), null);

Getting error on Route attribute in Api method

I have created Api controller and trying to add 1 api method but getting error when adding Route attribute on my api method:
This is my method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
public class MyController : ApiController
{
[AllowAnonymous]
[HttpPost]
[Route("api/abc/Get")] //Getting error :type or namespace Route could not be found
public async Task<object> Get()
{
}
}
My dll references:
But on Route Attribute i am getting error:
Error:Type or namespace Route could not be found
Probably you need to check if you have System.Web.Http assembly in your project references. if you used nuget please check if you have web api packages installed
you can check it here:

HttpApplicationState not available in an MVC controller

I'm using MVC2 and VS2010 developing a website and need to use Application State global values. I can set a value like 'Application["hits"]=0;' in Global.asax but when trying to use the same in an MVC controller always get the following error:
The name 'Application' does not exist in the current context
I have also tried using in the Global.asax in order to define a global variable but it triggers the following error:
A namespace cannot directly contain members such as fields or methods
I'm looking for a way to define global Application State values that are available within all controllers of my MVC2 web application. Am I omitting something? My controller looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCApplication.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
Application["hits"] += 1;
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
}
I appreciate any solutions and/or suggestions.
Thanks
Mehrdad
I think that in MVC3 you can get access to an actual HttpApplicationState object via the
HttpContext.ApplicationInstance
property. That is:
HttpApplicationState application = HttpContext.ApplicationInstance.Application
In ASP.NET MVC2, i use
HttpContext.Application["foo"] = "bar";
and to get
HttpContext.Application["foo"]
You could use a static class with an internal dictionary and an indexer.
Also, have you tried HttpContext.Current.Application?

Categories

Resources