System.Web.Http assembly not allways visible in same c# project - c#

I have a C# project where in my controller class the System.Web.Http library can be referenced but in the another class it cannot. The reference has been added to the overall project and both classes have all the necessary using directives.
The Request method of System.Web.Http cannot be resolved in some instances?
Here are code snippets of the two classes:
Controllers/FormsController.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using FormsImport.Models;
namespace FormsImport.Controllers
{
public class TCSTasksController : ApiController
{
[Route("api/TCSUploadFile")]
[AllowAnonymous]
public async Task<HttpResponseMessage> UploadCSVFile()
{
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created); // <-- the name Request does exists
.
.
.
}
CSVmanager.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http; //<-- Compiler claims this directive is unneccesary
using System.Web.Http.Description;
using FormsImport.Models;
namespace FormsImport
{
public class CSVmgr
{
public async Task<HttpResponseMessage> UploadCSVFile()
{
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created); // <-- the name Request Does not exist in the current context
.
.
.
}

I think you should agree with your compiler/IDE (Visual Studio?) in this case - it's simply pointing out that the referenced assembly is not in use in this class.
Should you decide to use any functionality from this assembly, the warning in question will go away.
EDIT based on comment: If the functionality you need is part of a protected interface of another class, such as ApiController, you MUST extend that class to access such functionality in your own class. If such extension subsequently uses methods in the assembly you referenced (and for which the compiler shows an unnecessary using directive), the compiler warning regarding the using directive will likewise resolve.

in your api controller, Request is a HttpRequestMessage type, and the CreateResponse is the extension method of HttpRequestMessage. why not create a HttpResponseMessage new instance in your CSVmgr class. like:
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;

codran 17 explained it the best.
My new class is not derived from the APIController Class and the Request method of that class is not a static function that I can call like System.IO.Path() for instance. So I must use another static function from a class that returns the same results or pass a reference to the APIController to my new class.
Like so:
public async Task<HttpResponseMessage> UploadCSVFile(ApiController controller)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = controller.Request.CreateResponse(HttpStatusCode.Created);

Related

REST Server connection reset on Routing path

Question is: Did I define the client resource call correctly, or is there something wrong in the server code?
I have a REST API server I am coding in C# / Visual Studio 2019 using the Web API template. I have 2 paths at the moment - a POST and a GET.
POST: /api/account
GET: /api/account/{accountid:long}
POST works great using SoapUI as a test client, but GET gives me a connection reset (message is "Error getting response; java.net.SocketException: Connection reset").
I hope I defined the resource correctly:
Here's my Controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using Coda.Core;
using CodaRESTServer.Models;
using System.IO;
using System.Diagnostics;
namespace MyRESTServer.Controllers
{
[RoutePrefix("api/account")]
public class AccountController : ApiController
{
[HttpGet]
[Route("{accountid:long}")]
// GET api/<controller>/5
public JObject Get(long accountid)
{
var x = new JObject();
x["worked"] = "true";
return (x);
}
[HttpPost]
[Route("")]
// POST api/account
public JObject Post()
{
var x = new JObject();
x["worked"] = "true";
return (x);
}
}
}
I specified it wrong in SoapUI. It needs to be:
/api/account/{accountid}
And then I can click on the Parameters field and enter the value.

Unable to access variables from another project

I am trying to automate API testing using c# (Restsharp). I have 2 projects in same solution. One project is a console app where I am trying to keep the methods, while the other one is a Unit Test Project where I plan on keeping the test cases.
I am able to access the methods from the BASE project by creating an object of the method, but unable to access the variables within that method to apply assertions. Any idea what am I missing?
(I am new to c#).
Method class in Base project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace Base
{
public class Methods
{
public void GetMethod(long ID)
{
var client = new RestClient("getUrl");
var request = new RestRequest(Method.GET);
request.AddParameter("userId", ID);
IRestResponse response = client.Execute(request);
HttpStatusCode statusCode = response.StatusCode;
int nStatusCode = (int)statusCode;
}
}
}
UnitTest class in Test project
using System;
using System.Net;
using Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RestSharp;
namespace Tests
{
[TestClass]
public class UnitTests
{
[TestMethod]
public void StatusOK()
{
//Arrange, Act, Assert
var methods = new Methods();
methods.GetMethod(2330013)
Assert.IsTrue(nStatusCode.Equals(200));
}
}
}
UnitTest is unable to read nStatusCode variable, as well as response variable.
I have already added dependency between the projects.
Appreciate the help!!
One option to address the problem is to make GetMethod return the status code:
public int GetMethod(long ID)
{
...
int nStatusCode = (int)statusCode;
return nStatusCode;
}
Then the test can examine the return value.
var c = methods.GetMethod(2330013)
Assert.AreEqual(200, c);
PS. I recommend using Assert.AreEqual instead of Assert.IsTrue because in the case the code is not 200 the test failure output will contain the bad value. With IsTrue you will only know that it wasn't 200 but you won't know what it was.

Get JSON data out of Umbraco

I am a frontend developer so forgive my lack of ability to explain my issue.
I am trying to create some pages in an Umbraco project that display data using Vue.js. For this, I am trying to set up a custom API controller that will return the data I want, when called.
A simple example would be that I want to return all blog articles. Below is the code I have currently got:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using System.Web.Http;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public string Test()
{
return "qwerty";
}
}
}
I've read numerous articles and just can't seem to grasp what I need to do to query Umbraco for the data I want back?
I've tried adding
var content = Umbraco.TypedContent(1122);
And then returning that but I get errors stating:
(local variable) Umbraco.Core.Models.IPublishedContent content
Cannot implicitly convert type 'Umbraco.Core.Models.IPublishedContent' to 'string'
I have then tried serialising the var content but I get stuck with:
Self referencing loop detected for property 'FooterCtalink' with type
'Umbraco.Web.PublishedContentModels.Blog'. Path
'ContentSet[0].FeaturedProducts[0].Features[0].ContentSet[0]'.
Any help would be fantastic!
EDIT:
I have no edited the controller to be like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
using System.Web.Mvc;
using DTOs.PostDTO;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public PostDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new PostDTO();
// 3. Pupulate your DTO
myDTO.Url = content.Url;
// 4. return it
return myDTO;
}
}
}
And created a DTO like so:
namespace DTOs.PostDTO
{
public class PostDTO
{
public string Url { get; set; }
}
}
However, when console logging my data after the ajax request, I only only getting 1122.
The issue is that you can't return a .NET Object in JSON that has the circular dependency.
To solve your problem, you can simply follow the below steps:
Create your own DTO & add required properties in that.
Fetch content from Umbraco API in C# & populate your custom DTO object.
Return that DTO from JsonResult.
Your code will look like below:
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public MyDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new MyDTO();
// 3. Pupulate your DTO
myDTO.SomeProperty = content.SomeProperty;
// 4. return it
return myDTO;
}
}
You are on the right track.
I think you need to return ActionResult instead of string.
Something like:
[HttpGet]
public ActionResult Test()
{
var content = Umbraco.TypedContent(1122);
return new JsonResult(content);
}
This should return the umbraco object as Json.

Microsoft Bot framework assembly references

I have the following code but from the Microsoft bot creation tutorial https://learn.microsoft.com/en-us/azure/bot-service/dotnet/bot-builder-dotnet-quickstart
When I copy and paste it my using statements don't seem to be being used when they should be in the example? I've tried adding the using statements it suggest but I don't think that is required. I have errors on [BotAuthentication] and Activity "Type or namespace name 'Activity' could not be found' etc
I have the nugget packages installed as well.
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Linq;
using System.Configuration;
using Microsoft.Bot.Builder.CognitiveServices.QnAMaker;
using System.Web.Services.Description;
using Microsoft.Bot.Builder.PersonalityChat;
using Microsoft.Bot.Builder.PersonalityChat.Core;
namespace BenTestBot
{
[BotAuthentication]
public class MessagesController : ApiController
{
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.GetActivityType() == ActivityTypes.Message)
{
//await Conversation.SendAsync(activity, () => new Qna_Rich_Cards.Dialogs.QnaDialog().DefaultIfException());
await Conversation.SendAsync(activity, () => new Dialogs.BasicPersonalityChatBotDialog().DefaultIfException());
}
else
{
await HandleSystemMessageAsync(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
If you have already installed the nuget packages then this should not be there.
Maybe you should check the version of the packages and try updating the packages.
For [BotAuthentication] and activity to work you need Microsoft.Bot.Connector; that is already there in your case so just try updating.

ASP.NET Syntax and conventions

I am reading Designing Evolvable Web APIs with ASP.NET. In one of the exercises, the book has me edit a Controller using Visual Studio. This is being done in ASP.NET using C#. The template I used was the standard ASP.NET web application API.
I have edited the controller to the way the book shows (although it does not seem to give very specific directions). Here is what my controller looks like.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using WebApplication4.Models;
using WebApplication4.Providers;
using WebApplication4.Results;
namespace WebApplication4.Controllers
{
public class GreetingController : ApiController
{
public string GetGreeting() {
return "Hello World!";
}
}
public static List<Greeting> _greetings = new List<Greeting>();
public HttpResponseMessage PostGreeting(Greeting greeting)
{
_greetings.Add(greeting);
var greetingLocation = new Uri(this.Request.RequestUri, "greeting/" + greeting.Name);
var response = this.Request.CreateResponse(HttpStatusCodeResult.Created);
response.Headers.Location = greetingLocation;
return response;
}
}
I get errors on:
_greetings: A namespace cannot directly contain members such as fields or methods
PostGreeting: A namespace cannot directly contain members such as fields or methods,
_greetings : does not exist in the current context
Request : <invalid-global-code> does not contain a definition for 'request',
Created: HttpStatusCodeREsult does not contain a definition for 'Created'
As the error is trying to tell you, your fields and methods must be inside the class.
Check your braces.
Your _greetings field needs to be part of the class, as well as the PostGreeting method, it seems you just closed "}" of the class a bit early.
MOve the "}" before the _greetings field to the end of the file, like:
namespace WebApplication4.Controllers
{
public class GreetingController : ApiController
{
public string GetGreeting() {
return "Hello World!";
}
public static List<Greeting> _greetings = new List<Greeting>();
public HttpResponseMessage PostGreeting(Greeting greeting)
{
_greetings.Add(greeting);
var greetingLocation = new Uri(this.Request.RequestUri, "greeting/" + greeting.Name);
var response = this.Request.CreateResponse(HttpStatusCodeResult.Created);
response.Headers.Location = greetingLocation;
return response;
}
}
}

Categories

Resources